package com.xinchuang.service.targetSystem.Impl.damage;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.xinchuang.common.Result;
import com.xinchuang.common.ResultUtil;
import com.xinchuang.entity.targetSystem.damage.*;
import com.xinchuang.entity.targetSystem.system.TargetSubType;
import com.xinchuang.entity.targetSystem.system.TargetType;
import com.xinchuang.manager.THurtEvaluateAmmunitionManager;
import com.xinchuang.manager.THurtEvaluateBasicManager;
import com.xinchuang.manager.THurtEvaluateSubManager;
import com.xinchuang.mapper.targetSystem.damage.THurtEvaluateAmmunitionMapper;
import com.xinchuang.mapper.targetSystem.damage.THurtEvaluateBasicMapper;
import com.xinchuang.mapper.targetSystem.damage.THurtEvaluateSubMapper;
import com.xinchuang.service.targetSystem.damage.THurtEvaluateService;
import com.xinchuang.vo.THurtEvaluateVo;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * HS评定标准
 */
@Service
@RequiredArgsConstructor
public class THurtEvaluateServiceImpl implements THurtEvaluateService {

    private final THurtEvaluateBasicMapper tHurtEvaluateBasicMapper;
    private final THurtEvaluateBasicManager tHurtEvaluateBasicManager;
    private final THurtEvaluateAmmunitionMapper tHurtEvaluateAmmunitionMapper;
    private final THurtEvaluateAmmunitionManager tHurtEvaluateAmmunitionManager;
    private final THurtEvaluateSubMapper tHurtEvaluateSubMapper;
    private final THurtEvaluateSubManager tHurtEvaluateSubManager;

    @Override
    @Transactional
    public Result addAndUpdateHurtEvaluate(THurtEvaluateVo tHurtEvaluateVo) {
        if (StringUtils.isBlank(tHurtEvaluateVo.getDestroyLevel())) {
            return ResultUtil.error(500, "破坏等级不能为空");
        }
        String tHurtEvaluateBasicId = "";
        tHurtEvaluateVo.setUpdateTime(LocalDateTime.now());
        if (StringUtils.isEmpty(tHurtEvaluateVo.getId())) {
            tHurtEvaluateBasicId = IdUtil.fastSimpleUUID();
            tHurtEvaluateVo.setId(tHurtEvaluateBasicId);
            // 主表(t_hurt_evaluate_basic)数据添加
            tHurtEvaluateBasicMapper.insert(tHurtEvaluateVo);
        } else {
            //修改主表数据
            tHurtEvaluateBasicId = tHurtEvaluateVo.getId();
            tHurtEvaluateBasicMapper.updateById(tHurtEvaluateVo);
            // 删除子表数据
            tHurtEvaluateAmmunitionMapper.delete(new LambdaQueryWrapper<THurtEvaluateAmmunition>().eq(THurtEvaluateAmmunition::getHurtEvaluateBasicId, tHurtEvaluateBasicId));
            tHurtEvaluateSubMapper.delete(new LambdaQueryWrapper<THurtEvaluateSub>().eq(THurtEvaluateSub::getHurtEvaluateBasicId, tHurtEvaluateBasicId));
        }
        // t_hurt_evaluate_ammunitiona表数据添加
        List<THurtEvaluateAmmunition> tHurtEvaluateAmmunitionList = tHurtEvaluateVo.getHurtEvaluateAmmunitionList();
        for (THurtEvaluateAmmunition tHurtEvaluateAmmunition : tHurtEvaluateAmmunitionList) {
            tHurtEvaluateAmmunition.setId(IdUtil.fastSimpleUUID());
            tHurtEvaluateAmmunition.setHurtEvaluateBasicId(tHurtEvaluateBasicId);
            tHurtEvaluateAmmunition.setUpdateTime(LocalDateTime.now());
        }
        tHurtEvaluateAmmunitionManager.saveBatch(tHurtEvaluateAmmunitionList);
        // t_hurt_evaluate_sub表数据添加
        List<THurtEvaluateSub> tHurtEvaluateSubList = tHurtEvaluateVo.getHurtEvaluateSubList();
        for (THurtEvaluateSub tHurtEvaluateSub : tHurtEvaluateSubList) {
            tHurtEvaluateSub.setId(IdUtil.fastSimpleUUID());
            tHurtEvaluateSub.setHurtEvaluateBasicId(tHurtEvaluateBasicId);
            tHurtEvaluateSub.setUpdateTime(LocalDateTime.now());
        }
        tHurtEvaluateSubManager.saveBatch(tHurtEvaluateSubList);
        return ResultUtil.success(tHurtEvaluateBasicId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHurtEvaluate(String id, boolean deleteStatus) {
        // 物理删除
        if (deleteStatus) {
            tHurtEvaluateBasicMapper.deleteById(id);
            tHurtEvaluateAmmunitionMapper.delete(new LambdaQueryWrapper<THurtEvaluateAmmunition>().eq(THurtEvaluateAmmunition::getHurtEvaluateBasicId, id));
            tHurtEvaluateSubMapper.delete(new LambdaQueryWrapper<THurtEvaluateSub>().eq(THurtEvaluateSub::getHurtEvaluateBasicId, id));
            // 逻辑删除
        } else {
            tHurtEvaluateBasicManager.update(new LambdaUpdateWrapper<THurtEvaluateBasic>()
                    .set(THurtEvaluateBasic::getDataStatus, 1)
                    .eq(THurtEvaluateBasic::getId, id)
            );
            tHurtEvaluateAmmunitionManager.update(new LambdaUpdateWrapper<THurtEvaluateAmmunition>().set(THurtEvaluateAmmunition::getDataStatus, 1).eq(THurtEvaluateAmmunition::getHurtEvaluateBasicId, id));
            tHurtEvaluateSubManager.update(new LambdaUpdateWrapper<THurtEvaluateSub>().set(THurtEvaluateSub::getDataStatus, 1).eq(THurtEvaluateSub::getHurtEvaluateBasicId, id));
        }
    }

    /**
     * @param pageSize
     * @param pageNum
     * @param targetTypeId     目标树id
     * @param destroyLevel     破坏等级
     * @param targetTypeSubId  打击子目标id
     * @param typeOfAmmunition 弹型弹种id
     * @return
     */
    @Override
    public Map<String, Object> listHurtEvaluate(Integer pageSize, Integer pageNum, String targetTypeId, String destroyLevel, String targetTypeSubId, String typeOfAmmunition) {
        Page<THurtEvaluateBasic> hurtEvaluateBasicPage = new Page<>(pageNum, pageSize);
        MPJLambdaWrapper<THurtEvaluateBasic> wrapper = new MPJLambdaWrapper<THurtEvaluateBasic>()
                .selectAll(THurtEvaluateBasic.class)
                .selectAs(DictionaryTable::getLabel, THurtEvaluateBasic::getDestroyLevelName)
                .selectCollection(THurtEvaluateAmmunition.class, THurtEvaluateBasic::getHurtEvaluateAmmunitionList, b -> b
                        .association(Missile.class, THurtEvaluateAmmunition::getTypeOfAmmunitionName))//一对多（一的base关联多的Amm表）
                .leftJoin(THurtEvaluateAmmunition.class, THurtEvaluateAmmunition::getHurtEvaluateBasicId, THurtEvaluateBasic::getId)
                .leftJoin(Missile.class, Missile::getId, THurtEvaluateAmmunition::getTypeOfAmmunition)
                .selectCollection(THurtEvaluateSub.class, THurtEvaluateBasic::getHurtEvaluateSubList, b -> b
                        .association(TargetSubType.class, THurtEvaluateSub::getSubTargetName))//一对多（一的base关联多的sub表）
                .leftJoin(THurtEvaluateSub.class, THurtEvaluateSub::getHurtEvaluateBasicId, THurtEvaluateBasic::getId)
                .leftJoin(TargetSubType.class, TargetSubType::getTypeId, THurtEvaluateSub::getTargetTypeSubId)
                .leftJoin(DictionaryTable.class, DictionaryTable::getValue, THurtEvaluateBasic::getDestroyLevel)//一对一（一的dictionary字典表关联一的base表的DestroyLevel字段）
                .eq(DictionaryTable::getType, "destroy_level")
                //条件
                .eq(StringUtils.isNotEmpty(targetTypeId), THurtEvaluateBasic::getTargetTypeId, targetTypeId)
                .eq(StringUtils.isNotEmpty(targetTypeSubId), THurtEvaluateSub::getTargetTypeSubId, targetTypeSubId)
                .eq(StringUtils.isNotEmpty(destroyLevel), THurtEvaluateBasic::getDestroyLevel, destroyLevel)
                .like(StringUtils.isNotEmpty(typeOfAmmunition), THurtEvaluateAmmunition::getTypeOfAmmunition, typeOfAmmunition)
                .eq(THurtEvaluateBasic::getDataStatus, 0);
        Page<THurtEvaluateBasic> pageList = tHurtEvaluateBasicMapper.selectPage(hurtEvaluateBasicPage, wrapper);
        //重写定义分页插件返回参数
        Map<String, Object> map = new HashMap<>();
        map.put("dataList", pageList.getRecords());
        map.put("total", pageList.getRecords().size());


//        // 查询出 过滤条件targetTypeSubId 打击子目标id、typeOfAmmunition 弹型弹种id 对应的主表（t_hurt_evaluate_basic）id列表
//        ArrayList<String> hurtEvaluateBasicIds = new ArrayList<>();
//        List<Object> hurtEvaluateBasicIdObjectsBySub = tHurtEvaluateSubMapper.selectObjs(new LambdaQueryWrapper<THurtEvaluateSub>()
//                .select(THurtEvaluateSub::getHurtEvaluateBasicId)
//                .eq(THurtEvaluateSub::getTargetTypeSubId,targetTypeSubId)
//        );
//        hurtEvaluateBasicIds.addAll(hurtEvaluateBasicIdObjectsBySub.stream().map(item -> item.toString()).collect(Collectors.toList()));
//        List<Object> hurtEvaluateBasicIdObjectsByAmmunition = tHurtEvaluateAmmunitionMapper.selectObjs(new LambdaQueryWrapper<THurtEvaluateAmmunition>()
//                .select(THurtEvaluateAmmunition::getHurtEvaluateBasicId)
//                .eq(THurtEvaluateAmmunition::getTypeOfAmmunition,typeOfAmmunition)
//        );
//        hurtEvaluateBasicIds.addAll(hurtEvaluateBasicIdObjectsByAmmunition.stream().map(item -> item.toString()).collect(Collectors.toList()));
//        // 过滤条件targetTypeSubId 打击子目标id、typeOfAmmunition 弹型弹种id 查询为空时，使用表中不存在的随机id查询，查询结果为空
//        if((StringUtils.isNotEmpty(targetTypeSubId) || StringUtils.isNotEmpty(typeOfAmmunition)) && hurtEvaluateBasicIds.size()==0){
//            hurtEvaluateBasicIds.add("0530862477ca48b1488c85d62a3b9b5c");
//        }
//        // 查询主表（t_hurt_evaluate_basic）
//        Page<THurtEvaluateBasic> tHurtEvaluateBasicPageInfo = new Page<>(pageNum, pageSize);
//        Page<THurtEvaluateBasic> tHurtEvaluateBasicPage = tHurtEvaluateBasicMapper.selectPage(tHurtEvaluateBasicPageInfo,
//                new LambdaQueryWrapper<THurtEvaluateBasic>()
//                        .eq(THurtEvaluateBasic::getDataStatus,0)
//                        .eq(THurtEvaluateBasic::getTargetTypeId, targetTypeId)
//                        .eq(StringUtils.isNotEmpty(destroyLevel),THurtEvaluateBasic::getDestroyLevel,destroyLevel)
//                        .in(StringUtils.isNotEmpty(targetTypeSubId) || StringUtils.isNotEmpty(typeOfAmmunition),THurtEvaluateBasic::getId,hurtEvaluateBasicIds)
//        );
//        List<THurtEvaluateBasic> tHurtEvaluateBasics = tHurtEvaluateBasicPage.getRecords();
//        ArrayList<THurtEvaluateVo> tHurtEvaluateVos = new ArrayList<>();
//        // 查询两个子表，子表A毁伤评定标准关联表(毁伤评定与子目标)t_hurt_evaluate_sub，子表B 毁伤评定标准关联表(弹型弹种关联)(t_hurt_evaluate_ammunition)
//        for (THurtEvaluateBasic tHurtEvaluateBasic : tHurtEvaluateBasics) {
//            String tHurtEvaluateBasicId = tHurtEvaluateBasic.getId();
//            THurtEvaluateVo tHurtEvaluateVo = new THurtEvaluateVo();
//            BeanUtils.copyProperties(tHurtEvaluateBasic,tHurtEvaluateVo);
//            List<THurtEvaluateAmmunition> tHurtEvaluateAmmunitions = tHurtEvaluateAmmunitionMapper.selectList(new LambdaQueryWrapper<THurtEvaluateAmmunition>()
//                    .eq(THurtEvaluateAmmunition::getDataStatus,0)
//                    .eq(THurtEvaluateAmmunition::getHurtEvaluateBasicId, tHurtEvaluateBasicId));
//            tHurtEvaluateVo.setHurtEvaluateAmmunitionList(tHurtEvaluateAmmunitions);
//            List<THurtEvaluateSub> tHurtEvaluateSubs = tHurtEvaluateSubMapper.selectList(new LambdaQueryWrapper<THurtEvaluateSub>()
//                    .eq(THurtEvaluateSub::getDataStatus,0)
//                    .eq(THurtEvaluateSub::getHurtEvaluateBasicId, tHurtEvaluateBasicId));
//            tHurtEvaluateVo.setHurtEvaluateSubList(tHurtEvaluateSubs);
//            tHurtEvaluateVos.add(tHurtEvaluateVo);
//        }
//        Page<THurtEvaluateVo> tHurtEvaluateVoPage = new Page<>();
//        BeanUtils.copyProperties(tHurtEvaluateBasicPage,tHurtEvaluateVoPage);
//        tHurtEvaluateVoPage.setRecords(tHurtEvaluateVos);
//        //重写定义分页插件返回参数
//        Map<String, Object> map = new HashMap<>();
//        map.put("dataList", tHurtEvaluateVoPage.getRecords());
//        map.put("total", tHurtEvaluateVoPage.getTotal());
        return map;
    }
}
